#!/usr/bin/env node

const http = require('http'),
      qs   = require('querystring'),
      fs   = require('fs'),
      log  = console.log;

let items =['eat','sleeping'],
    result = {
      status: 200,
      reason: 'ok',
    };//这里是返回的数据 给一个默认值

http.createServer((req, res) => {

  //./calc.js 3 4
  //3 + 4 = 7
  logRequest(req); //打印起始行和请求头

  if(req.url.slice(0,5) !== '/todo'){
    let html = fs.readFileSync('./12-todo.html').toString('utf8');

    if(req.url === '/') {
      res.end(html);
    }else if(req.url =='/12-todo.js'){
      fs.createReadStream('./12-todo.js').pipe(res);
    }
    else{
      res.end('not api request and not page request!'); 
    }
    //res.end('not api request!');
    return;
  } //非接口服务
  
  switch(req.method){
    case 'GET':
      select(req,res);
      //res.end('get method');
      break;

    case 'POST':
      insert(req, res);
      //res.end('post method');
      break;
      //curl -X POST -d 'item=eat' 加网址

    case 'PUT':
      update(req,res);
      //res.end('put method');
      break;

    case 'DELETE':
      remove(req,res);
      //res.end('delete method');
      break;

    default:
      res.end(`${res.method} method not support`);
  }

}).listen(8080);

function select(req,res){
  result.data = items;
  res.end(JSON.stringify(result));
}

function insert(req,res){
  let data = '';

  req.on('data',chunk => data += chunk);
  req.on('end',()=>{
    let item = qs.parse(data).item;

    if(item != '' && typeof item != undefined){
      items.push(item);
      res.end(JSON.stringify(result));
    }else{
      result.status = 401;
      result.reason = 'item is empty';
      res.end(JSON.stringify(result));
    }
  });
} 

function update(req,res){
  //get id
  let id = req.url.split(':')[1];
  //validate id
  //data type
  //value min = 0,max=items.length

  //get item
  let data = '';
  req.on('data',chunk => data += chunk);
  req.on('end',()=>{
    //update items[id] = item
    
    let item = qs.parse(data).item;
    if(item !== '' && typeof item != 'undefined' ){
      items[id] = item;
      res.end(JSON.stringify(result));
    }else{
      result.status = 402;
      result.reason = 'item is empty!';
      res.end(JSON.stringify(result));
    }
  });
}

function remove(req,res){
  //get id
  let id = req.url.split(':')[1];

  //id not exist  del all
  if(typeof id === 'undefined'){
    items =[];
    result.status = 200;
    result.reason = 'delete all success';
    res.end(JSON.stringify(result));
    return;
  }
  
  //id exist
  //valide id 验证id
  //id is ok  del items[id]
  items.splice(id,1);
  result.status = 200;
  result.reason = 'del success';
  res.end(JSON.stringify(result));
}

function logRequest(req){
  log(`$(req.method) $(req.url) HTTP/${req.httpVersion}`);
  log(req.headers);
  log();
}
